#!/bin/sh

BASEPATH=$(cd `dirname $0`; pwd)

APP_NAME=vhs
IS_DAEMON=

result=`echo $* | grep "\-d"`
if [ -n "$result" ]; then
	IS_DAEMON="-d"
fi

result=`echo $* | grep "\-w"`

#echo "IS_DAEMON: $IS_DAEMON"

ulimit -SHn 100000

setup_ld() {
	#echo "LD_LIBRARY_PATH: $LD_LIBRARY_PATH"
	result=`echo $LD_LIBRARY_PATH | grep "./lib"`
	if [ -n $result ]; then
		export LD_LIBRARY_PATH=.:./lib:$LD_LIBRARY_PATH
	fi
	
	result=`echo $LD_LIBRARY_PATH | grep "$BASEPATH"`
	if [ -n $result ]; then
		export LD_LIBRARY_PATH=$BASEPATH/lib:$BASEPATH:$LD_LIBRARY_PATH
	fi
	
	echo "LD_LIBRARY_PATH: $LD_LIBRARY_PATH"
}

start_app() {
	if [ -n "$IS_DAEMON" ]; then
		$BASEPATH/vhs -d &
	else
		$BASEPATH/vhs
	fi
}

stop_app() {
	PID=`ps -A | grep -i -e 'vhs$' | sed 's/^\([0-9]\{1,\}\).*/\1/g' |awk '{print $1}'`
	if [ -n "$PID" ]; then
		echo "kill $PID"
		kill $PID
	fi
	pkill $APP_NAME
}

if [ "$1" = "stop" ]; then
	stop_app
	exit
fi

if [ "$1" = "reload" ]; then
	stop_app
	IS_DAEMON="-d"
fi

if [ "$1" = "start" ]; then
	IS_DAEMON="-d"
fi

# modify LD_LIBRARY_PATH
setup_ld

# start app
start_app

